<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('multilingual.rejectedMaterial')" :rightText="$t('materials.rejectedMaterial')"
				@clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="barcodeSplitting page-auto" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<!-- 扫描条码部分 -->
				<view class="gui-bg-white gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('pageTranslation.returnedBarcodeInfo') }}
					</view>
					<!-- 添加盘点单号与创建时间start-->
					<view class="custom-card-itemTwo" >
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('finishedInventory.inventoryNumber')
						}}：</text>
						<comboGrid requestUrl="/wms/wmsCheckstockH/findCheckStockHForPda" v-model="data.countNumber"
							:requestParam="data.inventoryParam" inputKey="billCode"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" :gridPlaceholder="$t('Common.inputInventoryCalled')"
							:column="data.columnInventory.column" bindValue="billCode" @setClick="getInventoryClick">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo"  style="padding:10rpx 0">
						<text class="item-info-title">{{$t('finishedInventory.creationTime')}}：</text>
						<input style="margin: 8rpx 0;text-align: right;" class="gui-form-input" disabled
							v-model="data.creationTime" />
					</view>
					<!-- 添加盘点单号与创建时间end -->

					<view class="custom-card-itemTwo" style="padding:10rpx 0">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('distributedEnter.materialCode')
						}}：</text>
						<comboGrid requestUrl="/mes/basMaterial/getPageSetPDA" v-model="data.materialCode"
							:requestParam="data.materialParam" inputKey="materialName"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" :gridPlaceholder="$t('Common.enterCodeOrName')"
							:column="data.columnName.column" bindValue="materialName" @setClick="getMaterialClick">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding:10rpx 0">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('stockManage.purposeWarehouse')
						}}：</text>
						<comboGrid requestUrl="/wms/wmsWarehouse/getIsUsePageSetPDA" v-model="data.warehouseCode"
							:modelValue="data.warehouseName" :requestParam="data.warehouseParam" inputKey="warehouseName"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('pageTranslation.plsInputFilter')" :column="data.columnHome.column"
							bindValue="warehouseName" @setClick="handelGetClick" :rm="true"></comboGrid>
					</view>
					<!--  v-if="data.locationWarehouseId.length"  -->
					<view v-if="data.locationWarehouseId.length" class="custom-card-itemTwo" style="padding:10rpx 0">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('stockManage.purposeSeat')
						}}：</text>
						<!-- 有容量的库位 -->
						<comboGrid requestUrl="/wms/wmsLocation/getIsUsePageSetByWarehousePDA" v-model="data.locationName"
							:calculate="data.calculate" :requestParam="data.requestParam" inputKey="locationCode"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('pageTranslation.plsInputFilter')" :column="data.columnLocation.column"
							bindValue="locationName" @setClick="getLocationClick"></comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text class="required-color">*</text>{{
							$t('distributedEnter.materialQty') }}：</text>
						<uni-easyinput class="uni-mt-5" v-model="data.materialNumber" type="number"
							:placeholder="$t('hardwareOut.pleaseQty')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;width:140rpx"><text class="required-color">*</text>{{
							$t('pageTranslation.batchNo') }}：</text>
						<uni-easyinput class="uni-mt-5" v-model="data.batchNo" type="text" disabled="true"
							:placeholder="$t('JsInternational.enterBatch')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title" style="width:400rpx">{{ $t('pageTranslation.returnedBarcodeType')
						}}：</text>
						<comboGrid requestUrl="/mes/mesBillsRule/getPageSetPDA?code=bills_rule&flag=returnedMaterial"
							v-model="data.barcodeTypeName" :placeholder="$t('distributedEnter.placeholderTextChoose')"
							inputKey="code" :column="data.columnRule.column" bindValue="ruleCode" @setClick="getRuleClick">
						</comboGrid>
					</view>
					<view class="gui-form-item gui-border-b gui-flex gui-justify-content-center">
						<view class="gui-flex gui-space-between gui-align-items-center" style="width: 80%;height: 100rpx;">
							<button type="default" class="gui-button gui-button-mini gui-bg-black4 gui-noborder"
								style="width:200rpx;" @click="reset">
								<text class="gui-block gui-color-black gui-button-text-mini gui-icons">{{
									$t('distributedEnter.reset')
								}}</text>
							</button>
							<button type="default" class="gui-button gui-button-mini gui-bg-blue gui-noborder"
								style="width:200rpx;" @click="confirm">
								<text class="gui-block gui-color-white gui-button-text-mini gui-icons">{{
									$t('popup.confirm')
								}}</text>
							</button>
						</view>
					</view>
				</view>
				<!-- 提示信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('translationImage.materialsInformation')
					}}</text>
					<view class="gui-title-line"></view>
				</view>
				<!-- 卡片模块 -->
				<scroll-view :show-scrollbar="true" :scroll-y="true" class="scroll element-auto">
					<view style="height: 15rpx"></view>
					<view v-if="data.show" class="card-boxCustom">
						<view class="card-body" style="margin-bottom: 80rpx;">
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{ $t('pageTranslation.materialInfor') }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCoded') }}：</text>{{
									data.scanInfo.barCode
								}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCode') }}：</text>
								{{ data.scanInfo.materialCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialName') }}：</text>{{
									data.scanInfo.materialName
								}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
									data.scanInfo.materialSpec
								}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.uom') }}：</text>{{
									data.scanInfo.returnUnit
								}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.qty') }}：</text>{{
									data.scanInfo.returnQty
								}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.warehouse') }}：</text>{{
									data.scanInfo.sourceWarehouseCode
								}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.location') }}：</text>{{
									data.scanInfo.locationName
								}}
							</view>
						</view>
					</view>
				</scroll-view>
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="print">{{ $t('multilingual.print') }}
					</view>
				</view>
			</view>
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog :type="data.msgType" :cancelText="$t('translationImage.close')"
					:confirmText="$t('pageTranslation.toSet')" :title="$t('smashRemoval.warmPrompt')"
					:content="$t('pageTranslation.noDefaultLocation')" @confirm="dialogConfirm"></uni-popup-dialog>
			</uni-popup>
			<!-- 提交的二次弹框 -->
			<uni-popup ref="submitDialog" type="center">
				<view class="input-dialog-box" style="padding-left: 20rpx;">
					<view style="height: 15rpx"></view>
					<view class="card-body">
						<view class="custom-card-title">
							<text class="title-line"></text>
							{{ $t('materials.materialCategoryInformation') }}
						</view>
						<!-- 按照物料分类 -->
						<view class="secondaryBounced" v-for="(item, index) in data.secondaryBounced" :key="index">
							<view class="custom-card-itemOne">
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
										item.materialCode
									}}
								</view>
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('materials.materialsTotal') }}：</text>{{
										item.sum
									}}
								</view>
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('materials.totalNumberLabels') }}：</text>{{
									item.labelQty
								}}
							</view>
						</view>
					</view>

					<!-- 确定和取消 -->
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import { getDataDictionaryFn } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue';
import comboGrid from "@/components/comboGrid";
import { returnOfMaterial, saveOfMaterial, printsLabels1, printReturnRecord,findCheckStockHForPda } from '@/api/api.js'
import { useStore } from "vuex";
import { onShow } from '@dcloudio/uni-app';
import { DEFAULT_WAREHOUSECODE, DEFAULT_WAREHOUSENAME, DEFAULT_WAREHOUSEID, BIGBARCODER_PRINT } from '@/constant/index.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_SURE, OPERATION_REASCT, OPERATION_PRINT } from '@/constant/index.js'
import { PRINT_BASE_URL } from "@/constant/config.js"

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

let printUrl = PRINT_BASE_URL
//注册组件
components: { storageBin, comboGrid }
let alertDialog = ref(null)
let store = useStore();
let data = reactive({
	printSuccessFlag:true,
	calculate: false,// 是否是容量的数据
	// isCapacityBool:false,// 是否带容量 默认为false
	materialCode: "",//物料代码
	materialName: "",//物料名称
	warehouseName: "",//仓库名称
	locationName: "",//库位名称
	materialNumber: null,//数量
	barcodeTypeName: "",
	barcodeTypeCode: '',
	show: false,
	scanInfo: {},//存储后端返回的数据,card的信息
	residualCapacity: 0,//剩余容量
	lastInventory: 0,
	staticWarehouseCodeList: [],// 静态库位数组
	secondaryBounced: "",//二次弹框使用
	batchNo: "1",//批号
	inventoryParam:{
		billCode:"",
		text:'生产退料'
	},
	// 物料代码
	materialParam: {
		materialCode: "",
		materialName: "",//物料代码,传给接口用的变量
		text:"生产退料"
	},
	// 仓库
	warehouseParam: {
		warehouseName: "",//仓库
	},
	locationWarehouseId: uni.getStorageSync(DEFAULT_WAREHOUSEID) || '',//设置的默认仓库
	// 库位
	requestParam: {
		warehouseId: "",// 设置的默认仓库
		locationCode: "",
		locationTypeName: 'WarehouseLocation'
	},
	//物料代码下面的筛选
	columnName: {
		column: [{
			label: t('distributedEnter.materialCode'),
			name: "materialCode",
		}, {
			label: t('distributedEnter.materialName'),
			name: "materialName",
		}, {
			label: t('distributedEnter.materialSpec'),
			name: "specification",
		}]
	},
	//仓库代码下面的筛选
	columnHome: {
		column: [{
			label: t('distributedOut.warehouse'),
			name: "warehouseCode",
		}]
	},
	columnLocation: {
		column: [{
			label: t('distributedOut.volumnStockName'),
			name: "locationCode",
		}]
	},
	columnRule: {
		column: [{
			label: t('pageTranslation.barcodeType'),
			name: "ruleCode",
		}]
	},
	save: false,
	creationTime:'',//创建时间
	countNumber:'',//盘点单号
	columnInventory: {
		column: [{
			label: t('finishedInventory.inventoryNumber'),
			name: "billCode",
		}, {
			label: t('finishedInventory.creationTime'),
			name: "creationTime",
		}]}
})

//提交二次弹框
let submitDialog = ref(null);

const navHeight = computed(() => {
	return store.state.navHeight
})
onShow(async () => {
	getRequestData()
	//如果没有设置默认仓库则提示去设置默认仓库
	if (uni.getStorageSync(DEFAULT_WAREHOUSECODE) != 'RM'&&!data.locationWarehouseId.length) {
		alertDialogOpen()
		return
	}

	//没有设置默认打印机则去提示设置默认打印机
	data.defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	if (data.defaultValue == '') {
		uni.showModal({
			content: t('JsInternational.plsPrinter'),
			showCancel: false,
			confirmText: t('pageTranslation.toSet'),
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/setting/printer'
					})
				} else if (res.cancel) {

				}
			}
		});
	}

	//  获取盘点单号
	findCheckStockHForPda({billCode:''}).then(res=>{
		console.log(res)
		if(res.status==200){
			if(res.data?.rows?.length>0){
				data.countNumber=res.data.rows[0].billCode
				data.creationTime=res.data.rows[0].creationTime
			}
		}else{
			uni.showToast({ title: res.message, icon: "none" });
		}
	})

})

onMounted(() => {

})


const filter = async () => {
	// 查询目的仓库
	let locationCapacity = await getDataDictionaryFn('LocationCapacity')
	// console.log(locationCapacity)
	let bool = locationCapacity.some((item) => {
		// console.log(item)
		return item.value == data.warehouseCode
	})
	if (bool) {
		data.calculate = true
		// maxCapacity
		data.columnLocation = {
			column: [{
				label: t('JsInternational.volumnStockName'),
				name: "locationCode",
			}, {
				label: t('pageTranslation.volumeOfLocation'),
				name: "lastInventory",
			}]
		}
	} else {
		data.calculate = false
		data.columnLocation = {
			column: [{
				label: t('JsInternational.volumnStockName'),
				name: "locationCode",
			}]
		}
	}
}
watch(() => data.warehouseCode, (newVal, oldVal) => {
	filter()
}, {
	immediate: true,
	deep: true
});
//仓库设置默认值
const getRequestData = () => {
	// console.log(uni.getStorageSync(DEFAULT_WAREHOUSECODE) == 'RM')
	if (uni.getStorageSync(DEFAULT_WAREHOUSECODE) == 'RM') {
		data.warehouseCode = ""
		// data.warehouseName = ""
		data.requestParam.warehouseId = ""
		data.locationWarehouseId = ""

	} else {
		data.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '';
		data.warehouseName = uni.getStorageSync(DEFAULT_WAREHOUSENAME) || '';
		data.requestParam.warehouseId = uni.getStorageSync(DEFAULT_WAREHOUSEID) || '';
		data.locationWarehouseId = uni.getStorageSync(DEFAULT_WAREHOUSEID) || '';
	}
}
const alertDialogOpen = () => {
	// 延迟一秒调用用以解决弹框bug
	// setTimeout(() => {
	// 	alertDialog.value.open();
	// }, 500)
	uni.showModal({
		content: t('pageTranslation.noDefaultLocation'),
		showCancel: false,
		title: t('smashRemoval.warmPrompt'),
		confirmText: t('pageTranslation.toSet'),
		success: function (res) {
			if (res.confirm) {
				uni.navigateTo({
					url: '/pages/setting/warehouse'
				})
			} else if (res.cancel) {

			}
		}
	});

}

// 调整设置默认仓库
const dialogConfirm = () => {
	alertDialog.value.close();
	navigate({
		url: '/pages/setting/warehouse'
	})
}

// 盘点单号的选择
const getInventoryClick=(x)=>{
	console.log(x)
	data.countNumber=x.billCode
	data.creationTime=x.creationTime
	data.inventoryParam.billCode=x.billCode

}
//物料名称的选择
const getMaterialClick = (x) => {
	data.materialParam.materialCode = x.materialCode;
	data.materialParam.materialName = x.materialName;
	data.materialCode = x.materialCode;
	data.materialName = x.materialName;
	data.unit = x.unit
	data.materialSpec = x.specification
	data.materialId = x.id
}

// 获取选中的仓库的id
const handelGetClick = (x) => {
	data.warehouseId = x.id ? x.id : '';
	data.warehouseName = x.warehouseName ? x.warehouseName : '';
	data.warehouseCode = x.warehouseCode ? x.warehouseCode : '';
	// if(!Object.keys(x).length) return
	data.requestParam.warehouseId = x.id ? x.id + '' : '';
	data.locationWarehouseId = x.id ? x.id + '' : '';
	data.locationName = "";//仓库发生变化清空库位
}

//库位选择之后赋值给变量
const getLocationClick = (x) => {
	data.locationId = x.id
	data.locationName = x.locationCode;
	data.locationCode = x.locationCode;
}

//条码规则生成
const getRuleClick = (x) => {
	data.ruleCode = x.ruleCode;
	data.barcodeTypeCode = x.ruleCode;
	data.barcodeTypeName = x.ruleCode
}

//重置
const reset = () => {
	data.materialName = '';
	data.materialCode = '';
	data.warehouseName = '';
	data.locationName = '';
	data.materialNumber = null;
	data.barcodeTypeCode = "";
	data.barcodeTypeName = "";
	try {
		let inputParameter = '无'
		let returnParameter = '无'
		let operationPicture = '生产退料'
		let callInterface = '无'
		let opertionParmes = {
			inputParameter,
			returnParameter,
			operationPicture,
			callInterface,
			responseCode: '无',//返回状态
			errorMessage: '无',//错误信息
			isPass: 'Y',//是否成功 Y N
			operationType: OPERATION_REASCT
		}
		basPdaOperationLogFn(opertionParmes)
	} catch (error) {

	}
}

// 确定按钮 ,传递参数获取后端的数据返回的条码
const confirm = () => {
	console.log(data.ruleCode, data.materialName, data.locationName)
	if (data.materialNumber == null || Number(data.materialNumber) <= 0) {
		uni.showToast({ title: t('materials.quantityCannotNull'), icon: "none" });
		return
	}
	if (data.ruleCode == "" || data.ruleCode == undefined || data.materialName == "" || data.materialName == undefined || data.locationName == "" || data.batchNo == "") {
		uni.showToast({ title: t('JsInternational.plsInformation'), icon: "none" });
	} else {
		returnOfMaterial(data.ruleCode).then(res => {
			try {
				let inputParameter = JSON.stringify(data.ruleCode)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '生产退料'
				let callInterface = printUrl + "/print/RawMaterialBarCodePrint"
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode: res.status,//返回状态
					errorMessage: res.message,//错误信息
					isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType: OPERATION_SURE
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			console.log(res)
			data.show = true;
			// 将数据添加到data.scanInfo中
			data.scanInfo.barCode = res;
			data.scanInfo.materialName = data.materialName;
			data.scanInfo.materialCode = data.materialCode;
			data.scanInfo.materialSpec = data.materialSpec;
			data.scanInfo.returnUnit = data.unit;
			
			data.scanInfo.warehouseId = Number(data.warehouseId);
			data.scanInfo.warehouseName = data.warehouseName;
			data.scanInfo.sourceWarehouseCode = data.warehouseCode;
			// 库位信息
			data.scanInfo.locationId = Number(data.locationId);
			data.scanInfo.locationCode=data.locationCode
			data.scanInfo.locationName = data.locationName;
			data.scanInfo.sourceLocationCode = data.locationCode

			data.scanInfo.returnQty = Number(data.materialNumber);
			data.scanInfo.materialId = Number(data.materialId);
			data.scanInfo.barcodeTypeCode = data.barcodeTypeCode;
			data.scanInfo.barcodeTypeName = data.barcodeTypeName;
			data.scanInfo.batchNumber = data.batchNo;
			// 盘点单号 与创建时间
			data.scanInfo.billCode=data.countNumber
			data.scanInfo.creationTime=data.creationTime
			let item = {
				...data.scanInfo
			}
			store.commit('addforLabelingMaterialList', item)
			// 确定之后清空数据
			data.materialNumber = null
		})
	}
}

//统计物料个数
data.scanList = computed(() => {
	// console.log(store.state.forLabelingMaterialList,'data.scanList')
	return store.state.forLabelingMaterialList
})

// 数组中的对象安装某个属性分组
const groupBy = (array, key) => {
	const groups = {}
	array.forEach(function (o) {
		const group = o[key]
		groups[group] = groups[group] || []
		groups[group].push(o)
	})
	return Object.values(groups)
}

//打印 条码
const print = () => {
	console.log(data.scanList)
	if(data.countNumber==''){
		uni.showToast({ title: t('Common.notInventory'), icon: "none" });
		return
	}
	// secondaryBounced 二次弹框里面的数据读取 根据物料号进行分组
	data.secondaryBounced = groupBy(data.scanList, 'materialCode')
	for (let i = 0; i < data.secondaryBounced.length; i++) {
		data.secondaryBounced[i].sum = 0;//物料总数
		data.secondaryBounced[i].materialCode = data.secondaryBounced[i][0].materialCode; //物料代码
		data.secondaryBounced[i].labelQty = data.secondaryBounced[i].length;
		data.secondaryBounced[i].forEach(item => {
			data.secondaryBounced[i].sum = data.secondaryBounced[i].sum + Number(item.returnQty) //物料分类的数量总和
		})
	}
	// console.log(data.secondaryBounced)
	if (JSON.stringify(data.scanInfo) == "{}") {
		uni.showToast({ title: t('JsInternational.plsInput'), icon: "none" });
	} else {
		// 打开二次弹框
		submitDialog.value.open();

	}
}

// 保存打印的条码信息
const saveBarcode = () => {
	saveOfMaterial(
		data.scanList //data.scanInfo
	).then(res => {
		console.log(res.status == 200)
		try {
			let inputParameter = JSON.stringify(data.scanList)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '生产退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_PRINT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.status == 200) {
			// 打开弹框 提交的二次弹框
			console.log('条码保存和打印成功')
			// submitDialog.value.open();
			data.save = true
		} else if (res.statusCode == 300) {
			uni.showToast({ title: res.message, icon: "none" });
			data.save = false
		};
	})
	return data.save
}

//二次弹框的确定按钮
const confirmFn = () => {
	// 点击确定的时候保存条码并执行打印
	// 定义打印标签需要的生成日期
	var produceDate = (new Date()).getFullYear() + "/" + ((new Date()).getMonth() + 1) + "/" + (new Date()).getDate();
	submitDialog.value.close();//关闭二次弹框
	let list = data.scanList
	uni.showLoading({
		title: t('materials.connecting')
	});
	function testPromise(item) {
		return new Promise((resolve, reject) => {
			// console.log(item)
			let parmase = {
				barCode: item.barCode,
				materialCode: item.materialCode,
				materialName: item.materialName,
				specification: item.materialSpec,
				LocationCode:item.locationCode,
				produceDate: produceDate || '', // 生产日期
				hostid: item.equipmentCode || '', //机台
				qty: item.returnQty,
				unit: item.returnUnit, //单位
				printerName: data.defaultValue //打印机名字
			}
			console.log(parmase)
			printsLabels1(parmase).then(res => {
				try {
					let inputParameter = JSON.stringify(parmase)
					let returnParameter = JSON.stringify(res)
					let operationPicture = '生产退料'
					let callInterface = printUrl + '/print/barCodePrint'
					let opertionParmes = {
						inputParameter,
						returnParameter,
						operationPicture,
						callInterface,
						responseCode: res.status,//返回状态
						errorMessage: res.message,//错误信息
						isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
						operationType: OPERATION_SURE
					}
					basPdaOperationLogFn(opertionParmes)
				} catch (error) {
				}
				console.log(res, 'reessss')
				uni.hideLoading();
				if (res.status == 200) {
					//打印成功之后调用保存
					uni.showToast({ title: t('JsInternational.printSuccessfully'), icon: "none" });
					resolve(item);
				} else {
					data.printSuccessFlag = false;
					uni.showToast({ title: res.message, icon: "none" });
					reject()
				}
			})
		});
	}
	if(data.printSuccessFlag){
		saveBarcode();
	}else{
		uni.showToast({ title: res.message, icon: "none" });
	}
	let result = list.reduce((accumulatorPromise, item) => {
		return accumulatorPromise.then(() => {
			return testPromise(item);
		});
	}, Promise.resolve());
	result.then(e => {
		uni.hideLoading();
		data.scanInfo = {}
		data.show = false
		store.commit("clearforLabelingMaterialList");//提交成功清空vuex中的数据，同时领料数量也会自动清空
		data.materialName = ""
		data.materialCode = ""
		data.barcodeTypeName = ""
		data.materialNumber = null
		data.locationName = ""
		data.batchNo = ""
		data.countNumber=''
		data.creationTime=''
		console.log("All Promises Resolved !!")
	});

}

// 弹框的取消按钮
const cancelFn = () => {
	submitDialog.value.close();

}

// 页面跳转到查看记录
const clickRight = () => {
	navigate({
		url: '/pages/forLabeling/forLabelingRecord'
	})
}

//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit("clearforLabelingMaterialList")
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.secondaryBounced {
	margin-right: 20rpx;
	border-bottom: 2rpx solid rgb(155, 149, 149);
}
</style>
